/*
 * @Descripttion: 
 * @Author: Cxy
 * @Date: 2022-08-23 09:17:41
 * @LastEditors: Cxy
 * @LastEditTime: 2022-08-30 12:07:41
 * @FilePath: \ehomes-admind:\giteeBlog\blogServe\router\humanface.js
 */
const util = require('util')
const exec = util.promisify(require('child_process').exec)
const path = require('path')
const multer = require('multer')
const fs = require('fs')
const { findC } = require('./code')
const { find } = require('../mongo/db')
const { signJwt } = require('../jwt')

// 获取绝对路径face
const face_Path = path.resolve('./face')

/** @description: 训练人脸模型 */
const faceEntry = async (req, res) => {
  const storage = multer.diskStorage({
    destination: function (_, _, cb) {
      const filePath = './face/faceImg'
      if (!fs.existsSync(filePath)) {
        fs.mkdirSync(filePath, { recursive: true })
      }
      cb(null, filePath)
    },
    filename: function (req, file, cb) {
      cb(null, file.originalname.replace(/\./g, '.' + Date.parse(new Date()) / 1000 + '.'))
    }
  })
  const upload = multer({ storage }).array('file');
  upload(req, res, async err => {
    if (err) throw err
    const { stdout } = await exec('python ' + face_Path + '/modelTraining.py --facepath ' + face_Path)
    res.send(JSON.parse(String(stdout)))
  })
}


const { spawn } = require('child_process')
/** @description: 人脸识别 */
const faceLogin = async (req, res) => {
  const files = fs.readdirSync(face_Path + '/faceImg')
  const { faceImgBase64 } = req.body
  const py = spawn('python', [face_Path + '/faceRecognition.py'])
  py.stdin.write(JSON.stringify({ faceImgBase64, facePath: face_Path }))
  py.stdin.end()
  py.stdout.on('data', async function (resPy) {
    const { code, id } = JSON.parse(resPy.toString())
    if (code === 400) return res.send({ code: findC.loginC, massage: '未查到人脸数据' })
    if (code === 401) return res.send({ code, massage: '人脸有误请重新验证' })
    const loginData = files.filter(c => c.split('.')[1] === String(id))
    if (loginData[0]) {
      const admin_Code = loginData[0].split('.')[0]
      const { data: user_Data } = await find('users', { admin_Code })
      const token = signJwt(user_Data[0].pass_Word, 1)
      if (user_Data[0].frozen_State === 1) return res.send({ massage: '登录账户已冻结', code: 405 })
      const Users = user_Data.map(c => {
        const { admin_Code, admin_level, created_At, nick_Name, head_Portrait, brief_Introduction, My_Qq, My_Wb, My_Wx, My_Reward_Wx, My_Reward_Zfb } = c
        return { admin_Code, admin_level, created_At, nick_Name, head_Portrait, brief_Introduction, My_Qq, My_Wb, My_Wx, My_Reward_Wx, My_Reward_Zfb, token }
      })[0]
      if (user_Data[0].online_Offline === 0) {
        res.send({ massage: '登陆成功', Users, code: 200 })
      } else {
        res.send({ massage: '账号已在其他位置登录，是否强制登录', code: 400, Users, socket_Id: user_Data[0].socket_Id })
      }
    } else {
      res.send({ massage: '账号未注册，请注册后登录', code: 403 })
    }
  })
  py.stderr.on('data', function (data) {
    console.log('stderr: ' + data)
  });
  py.on('close', function (code) {
    console.log('子进程已退出，退出码 ' + code)
  });
}

module.exports = { faceEntry, faceLogin }